﻿using System;
using System.Text;
using ProdControls.NativePatterns.MessageConstants;
using ProdControls.Utility;

namespace ProdControls
{
    /// <summary>
    ///   Provides methods to interact with Textbox controls via the UI Automation API
    /// </summary>
    internal static class ProdTextBoxNative
    {
        /// <summary>
        ///   Uses SendMessage to try and get the text value
        /// </summary>
        /// <param name="windowHandle"> handle to the control </param>
        /// <returns> A string containing the text, null if a recoverable error occurred </returns>
        internal static string GetTextNative(IntPtr windowHandle)
        {
            StringBuilder sb = new StringBuilder();

            NativeMethods.SendMessage(windowHandle, (int) WindowMessages.WM_GETTEXT, sb.Capacity, sb);

            return sb.ToString();
        }

        /// <summary>
        ///   Uses SendMessage to set and verify the text value.
        /// </summary>
        /// <param name="windowHandle"> handle to the control </param>
        /// <param name="newText"> Desired text </param>
        /// <returns> true if successful, false if failure </returns>
        internal static bool SetTextNative(IntPtr windowHandle, string newText)
        {
            return NativeMethods.SendMessage(windowHandle, (int) WindowMessages.WM_SETTEXT, 0, newText) == 1 &&
                   VerifyText(windowHandle, newText);
        }

        /// <summary>
        ///   Verifies the text.
        /// </summary>
        /// <param name="windowHandle"> The window handle. </param>
        /// <param name="newText"> The new text. </param>
        /// <returns> </returns>
        private static bool VerifyText(IntPtr windowHandle, string newText)
        {
            string currentValue = GetTextNative(windowHandle);

            return string.Compare(currentValue, newText, false) == 0;
        }
    }
}